package com.leecode.xiehf.page_02;

import com.leecode.Printer;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 给定一个二叉树，判断其是否是一个有效的二叉搜索树。
 *
 * 假设一个二叉搜索树具有如下特征：
 *
 * 节点的左子树只包含小于当前节点的数。
 * 节点的右子树只包含大于当前节点的数。
 * 所有左子树和右子树自身必须也是二叉搜索树。
 * https://leetcode-cn.com/problems/validate-binary-search-tree/
 */
public class Solution_0098 extends Printer {

    public static void main(String[] args) {
        Solution_0098 solution = new Solution_0098();
        boolean s = solution.isValidBST(new TreeNode(2, new TreeNode(1, null, null),
                new TreeNode(3, null, null)));
        print(s);
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    /**
     *
     * @param root
     * @return
     */
    public boolean isValidBST(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return true;
        }
        traversal(list, root.left);
        list.add(root.val);
        traversal(list, root.right);
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            if (list.get(i) >= list.get(i+1)) {
                return false;
            }
        }
        return true;
    }

    private void traversal(List<Integer> list, TreeNode node) {
        if (node == null) {
            return;
        }
        traversal(list, node.left);
        list.add(node.val);
        traversal(list, node.right);
    }
}
